import { defineStore } from 'pinia'
import { login, logout, refreshToken, validateToken } from '@/api/admin'
import { ElMessage } from 'element-plus'

export const useAdminStore = defineStore('admin', () => {
  // 状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const refreshTokenValue = ref(localStorage.getItem('admin_refresh_token') || '')
  const userInfo = ref(null)
  const isLoggedIn = ref(false)

  // 登录
  const adminLogin = async (loginForm) => {
    try {
      const { data } = await login(loginForm)
      
      // 存储token和用户信息
      token.value = data.token
      refreshTokenValue.value = data.refreshToken
      userInfo.value = data.userInfo
      isLoggedIn.value = true
      
      // 持久化存储
      localStorage.setItem('admin_token', data.token)
      localStorage.setItem('admin_refresh_token', data.refreshToken)
      localStorage.setItem('admin_user_info', JSON.stringify(data.userInfo))
      
      ElMessage.success('登录成功')
      return data
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      throw error
    }
  }

  // 登出
  const adminLogout = async () => {
    try {
      if (token.value) {
        await logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除状态
      token.value = ''
      refreshTokenValue.value = ''
      userInfo.value = null
      isLoggedIn.value = false
      
      // 清除本地存储
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_refresh_token')
      localStorage.removeItem('admin_user_info')
      
      ElMessage.success('已退出登录')
    }
  }

  // 刷新Token
  const refreshAccessToken = async () => {
    try {
      if (!refreshTokenValue.value) {
        throw new Error('没有刷新令牌')
      }
      
      const { data } = await refreshToken(refreshTokenValue.value)
      
      // 更新token
      token.value = data.token
      refreshTokenValue.value = data.refreshToken
      userInfo.value = data.userInfo
      
      // 持久化存储
      localStorage.setItem('admin_token', data.token)
      localStorage.setItem('admin_refresh_token', data.refreshToken)
      localStorage.setItem('admin_user_info', JSON.stringify(data.userInfo))
      
      return data
    } catch (error) {
      // 刷新失败，清除所有状态
      await adminLogout()
      throw error
    }
  }

  // 验证Token
  const validateAccessToken = async () => {
    try {
      if (!token.value) {
        return false
      }
      
      const { data } = await validateToken()
      return data
    } catch (error) {
      return false
    }
  }

  // 初始化用户信息
  const initUserInfo = () => {
    const storedUserInfo = localStorage.getItem('admin_user_info')
    const storedToken = localStorage.getItem('admin_token')
    
    if (storedUserInfo && storedToken) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
        isLoggedIn.value = true
      } catch (error) {
        console.error('解析用户信息失败:', error)
        adminLogout()
      }
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    if (!userInfo.value) return false
    
    // 管理员拥有所有权限
    if (userInfo.value.role === 'admin') return true
    
    // 其他权限检查逻辑
    return true
  }

  return {
    token,
    refreshTokenValue,
    userInfo,
    isLoggedIn,
    adminLogin,
    adminLogout,
    refreshAccessToken,
    validateAccessToken,
    initUserInfo,
    hasPermission
  }
})